package View;

import Mysql.ShareData;
import client.ClientManager;
import instruction.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.stage.StageStyle;
import javafx.util.Callback;


import java.io.*;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class MainWindow extends window {
    private UserData userData;
    private ClientManager clientManager;
    private ListView<Friend> friendList;
    private ListView<Variety> messageList;
    private ListView<Group> groupList;
    private ObservableList<Friend> friendData = FXCollections.observableArrayList();
    private ObservableList<Group> groupData = FXCollections.observableArrayList();
    private ObservableList<Variety> messageData=FXCollections.observableArrayList();
    private ImageView imageView;//消息提示

    public UserData getUserData() {
        return userData;
    }

    public void setUserData(UserData userData) {
        this.userData = userData;
    }

    public ClientManager getClientManager() {
        return clientManager;
    }

    public void setClientManager(ClientManager clientManager) {
        this.clientManager = clientManager;
    }
    public ObservableList<Friend> getFriendData() {
        return friendData;
    }

    public ObservableList<Group> getGroupData() {
        return groupData;
    }

    public ObservableList<Variety> getMessageData() {
        return messageData;
    }

    public ImageView getImageView() {
        return imageView;
    }

    public void setImageView(ImageView imageView) {
        this.imageView = imageView;
    }

    public MainWindow() throws IOException, SQLException {
        root = FXMLLoader.load(getClass().getResource("/Fxml/main.fxml"));
        Scene scene = new Scene(root, 332, 559);
        scene.setFill(Color.TRANSPARENT);
        setScene(scene);
        initStyle(StageStyle.TRANSPARENT);
        setResizable(false);
        setTitle("We Chat");
        friendList = ((ListView) $("friendList"));
        messageList = ((ListView) $("messageList"));
        groupList = ((ListView) $("groupList"));
        Image image=new Image("/Picture/sourceMaterial/主界面背景图.jpg",341,211,false,false);
        ((ImageView)$("backgroundImage")).setImage(image);
        move();
        quit();
        setIcon();
        minimiser();
    }

    @Override
    public void quit() {
        ((Button) $("exitButton")).setTooltip(new Tooltip("退出"));
        ((Button) $("exitButton")).setOnAction(event -> {
            close();
            System.exit(0);
        });
    }

    @Override
    public void minimiser() {
        ((Button) $("ministerButton")).setTooltip(new Tooltip("最小化"));
        ((Button) $("ministerButton")).setOnAction(event -> {
            setIconified(true);
        });
    }

    public void setUserData(String id, String text) {
        ((Label) $(id)).setText(text);
    }

    public void InitialUserData() {
        ((Label) $("userAccount")).setText(userData.getUser().getAccount());
        ((Label) $("userName")).setText(userData.getUser().getNickname());
        ((Label) $("userSign")).setText(userData.getUser().getSignature());
        ((Label) $("userOnline")).setText("在线");
        ((ImageView) $("imagePhoto")).setImage(new Image(userData.getUser().getHead(), 80, 80, false, false));
        Circle circle1 = new Circle();
        circle1.setRadius(40);
        circle1.setCenterX(40);
        circle1.setCenterY(40);
        ((ImageView) $("imagePhoto")).setClip(circle1);

    }

    public void InitialFriendList() {
        friendList.setItems(friendData);
        friendList.setFixedCellSize(40);
        friendList.setCellFactory(new Callback<ListView<Friend>, ListCell<Friend>>() {
            @Override
            public ListCell<Friend> call(ListView<Friend> param) {
                ListCell<Friend> listCell;
                listCell = new ListCell<Friend>() {
                    @Override
                    protected void updateItem(Friend item, boolean empty) {
                        super.updateItem(item, empty);

                        if (!empty && item != null)//当单元格有数据时
                        {
                            HBox hbox = new HBox(10);//水平布局
                            //显示头像
                            ImageView iv = new ImageView(new Image(item.getMember().getHead(), 40, 40, false, false));
                            Circle circle1 = new Circle();
                            circle1.setRadius(20);
                            circle1.setCenterX(20);
                            circle1.setCenterY(20);
                            iv.setClip(circle1);
                            //显示好友账号和备注
                            Label label = new Label(item.getMember().getAccount() + " (" + item.getFriendRemarks() + ")");
                            label.setFont(new Font(18));
                            //放入水平布局
                            hbox.getChildren().addAll(iv, label);
                            this.setGraphic(hbox);
                        } else {
                            setText(null);
                            setGraphic(null);
                        }
                    }
                };
                return listCell;
            }
        });
    }

    public void InitialGroupList() {
        groupList.setItems(groupData);
        groupList.setFixedCellSize(40);
        groupList.setCellFactory(new Callback<ListView<Group>, ListCell<Group>>() {
            @Override
            public ListCell<Group> call(ListView<Group> param) {
                ListCell<Group> listCell;
                listCell = new ListCell<Group>() {
                    @Override
                    protected void updateItem(Group item, boolean empty) {
                        super.updateItem(item, empty);

                        if (!empty && item != null)//当单元格有数据时
                        {
                            HBox hbox = new HBox(10);//水平布局
                            //显示头像
                            ImageView iv = new ImageView(new Image(item.getImage(), 40, 40, false, false));
                            Circle circle1 = new Circle();
                            circle1.setRadius(20);
                            circle1.setCenterX(20);
                            circle1.setCenterY(20);
                            iv.setClip(circle1);
                            //显示群聊账号和备注
                            Label label = new Label(item.getAccount() + " (" + item.getName() + ")");
                            label.setFont(new Font(18));
                            //放入水平布局
                            hbox.getChildren().addAll(iv, label);
                            this.setGraphic(hbox);
                        } else {
                            setText(null);
                            setGraphic(null);
                        }
                    }
                };
                return listCell;
            }
        });
    }
    public void InitialMessageList() {
        messageList.setItems(messageData);
        messageList.setFixedCellSize(40);
        messageList.setCellFactory(new Callback<ListView<Variety>, ListCell<Variety>>() {
            @Override
            public ListCell<Variety> call(ListView<Variety> param) {
                ListCell<Variety> listCell = new ListCell<Variety>() {
                    @Override
                    protected void updateItem(Variety item, boolean empty) {
                        super.updateItem(item, empty);
                        if (!empty && item != null)//当单元格有数据时
                        {
                            //群消息
                            if (item.getType().equals("group")) {
                                HBox hbox = new HBox(10);//水平布局
                                //显示头像
                                ImageView iv = new ImageView(new Image(item.getGroup().getImage(), 40, 40, false, false));
                                Circle circle1 = new Circle();
                                circle1.setRadius(20);
                                circle1.setCenterX(20);
                                circle1.setCenterY(20);
                                iv.setClip(circle1);
                                //显示账号和消息
                                Label label = new Label(item.getGroup().getName());
                                label.setFont(new Font(18));
                                //放入水平布局
                                hbox.getChildren().addAll(iv, label);
                                this.setGraphic(hbox);
                            }else if(item.getType().equals("friend")){
                                    HBox hbox = new HBox(10);//水平布局
                                    //显示头像
                                    ImageView iv = new ImageView(new Image(item.getFriend().getMember().getHead(), 40, 40, false, false));
                                    Circle circle1 = new Circle();
                                    circle1.setRadius(20);
                                    circle1.setCenterX(20);
                                    circle1.setCenterY(20);
                                    iv.setClip(circle1);
                                    //显示好友账号和备注
                                    Label label = new Label(item.getFriend().getFriendRemarks());
                                    label.setFont(new Font(18));
                                    //放入水平布局
                                    hbox.getChildren().addAll(iv, label);
                                    this.setGraphic(hbox);
                            }
                        } else {
                            setText(null);
                            setGraphic(null);
                        }
                    }
                };
                return listCell;
            }
        });
    }

    public void loadData() throws SQLException, IOException {
        //将好友列表载入数据
       ArrayList<Friend> friendList = userData.getFriendList();//存储好友的容器
        ArrayList<ArrayList<Message>> privateRecord=userData.getChatMessageRecord();//存储私聊消息记录的容器
        for (Friend friend:friendList) {
            friendData.add(friend);//载入好友单元格
            Variety variety = new Variety("friend");//载入消息单元格
            variety.setFriend(friend);
            messageData.add(variety);//载入消息单元格
            String account = friend.getMember().getAccount();//找到好友账号
            ChatWindow chatWindow = new ChatWindow(this, clientManager, friend);//new一个聊天窗口
            ObservableList<Message> chatMessage = chatWindow.getPrivateMessageData();//找到相应的承载消息的容器
            for (ArrayList<Message> record : privateRecord) {//通过遍历找到相应的好友的消息记录
                String sender=null;
                String receiver=null;
                if(record.size()!=0){
                    sender=record.get(0).getPrivateMessage().getSendAccount();
                    receiver=record.get(0).getPrivateMessage().getReceiveAccount();
                }else{
                    break;
                }
                if (account.equals(sender) || account.equals(receiver)) {
                    for (Message message : record) {//载入数据
                        String type = message.getPrivateMessage().getType();
                        if (type.equals("picture")) {
                            InputStream input = new ByteArrayInputStream(message.getPrivateMessage().getPicture());
                            File file = new File("D:\\project1\\pictureData\\" + message.getPrivateMessage().getContent());
                            int temp;
                            FileOutputStream fos = new FileOutputStream(file);
                            while ((temp = input.read()) != -1) {
                                fos.write(temp);
                            }
                            input.close();
                            fos.close();
                            File image = new File("D:\\project1\\pictureData\\" + message.getPrivateMessage().getContent());
                            message.getPrivateMessage().setContent("file:///" + image.getAbsolutePath());
                        }
                        chatMessage.add(message);
                    }
                }else {
                    break;
                }
            }
            ShareData.chatWindowList.add(chatWindow);//存储窗口，方便点击弹出
        }
        //将群聊列表载入数据
        ArrayList<Group> groupList=userData.getGroupList();//存储群的容器
        ArrayList<ArrayList<Message>> groupRecord=userData.getGroupMessageRecord();//存储群聊记录的容器
        for(Group group:groupList){
            groupData.add(group);
            Variety variety=new Variety("group");//载入消息单元格
            variety.setGroup(group);
            messageData.add(variety);
            String account=group.getAccount();
            GroupChatWindow groupChatWindow=new GroupChatWindow(this,clientManager,userData.getUser(),group);//new 一个聊天窗口
            ObservableList<Message> groupMessage=groupChatWindow.getGroupMessageData();//找到相应的承载消息的容器
            for(ArrayList<Message> record:groupRecord){
                String receiver;
                if(record.size()!=0){
                receiver=record.get(0).getGroupMessage().getReceiver();
                }else{
                    break;
                }
                if(account.equals(receiver)){
                    for(Message message:record){
                        String type = message.getGroupMessage().getType();
                        if (type.equals("picture")) {
                            InputStream input = new ByteArrayInputStream(message.getGroupMessage().getPicture());
                            File file = new File("D:\\project1\\pictureData\\" + message.getGroupMessage().getContent());
                            int temp;
                            FileOutputStream fos = new FileOutputStream(file);
                            while ((temp = input.read()) != -1) {
                                fos.write(temp);
                            }
                            input.close();
                            fos.close();
                            File image = new File("D:\\project1\\pictureData\\" + message.getGroupMessage().getContent());
                            message.getGroupMessage().setContent("file:///" + image.getAbsolutePath());
                        }
                        groupMessage.add(message);
                    }
                }else{
                    break;
                }
            }
            ShareData.groupChatWindowList.add(groupChatWindow);
        }
    }
    public void InitialAssembly(){
        ((MenuButton)$("searchButton")).getItems().get(0).setText("搜索好友");
        ((MenuButton)$("searchButton")).getItems().get(1).setText("搜索群聊");
    }
}
